package com.sam.im.heiqun.uis.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.pay.PayResult;
import com.sam.im.heiqun.entities.weixinAPPIDInfo;
import com.sam.im.heiqun.entities.weixinAPPIDbean;
import com.sam.im.heiqun.entities.weixinBean;
import com.sam.im.heiqun.entities.weixinQRData;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.pay.WXPay;
import com.sam.im.heiqun.uis.beans.RechargeOrderBean;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.sam.im.heiqun.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.ILog;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class RechargeActivity extends BaseSwipeBackActivity implements TextWatcher {

    private static final String TAG = RechargeActivity.class.getSimpleName();

    @BindView(R.id.money)
    EditText money;

    @BindView(R.id.next)
    Button next;

    @BindView(R.id.money_type)
    TextView moneyType;

    private String type;


    @Override
    public int getContentViewId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.recharge);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        type = getIntent().getStringExtra("type");
        money.addTextChangedListener(this);
        next.setAlpha(0.5f);
        next.setEnabled(false);

        if ("0".equals(type)) {//微信支付
            moneyType.setText("￥");
        } else {
            moneyType.setText("￥");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer refresh) {
        if (refresh == EventBusType.RESULT_PAY_WX_SUCCESS) {
            finish();
        }
    }

    @OnClick({R.id.next})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.next:
                doNext();
                break;
        }
    }

    private void doNext() {
        final String moneyStr = money.getText().toString().trim();
        if ("".equals(moneyStr)) {
            return;
        }

        String payInfo = ToolsUtils.getUser().getPayInfo();
        if (payInfo == null || payInfo.equals("")) {
            new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.tip_psw)).setMessage(getResources().getString(R.string.no_pay_psw)).setNegativeButton(getString(R.string.cancel), null).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(RechargeActivity.this, IdentityProvingActivity.class);
                    intent.putExtra("money", moneyStr);
                    intent.putExtra("type", type);
//                    showToast("type001="+type);
                    startActivity(intent);
                }
            }).create().show();
        } else {

            if ("1".equals(type)) {  // 海外支付
//                doOverSeasPay(moneyStr);
                double mmo = Double.parseDouble(moneyStr);
                setPayZFB("" + mmo);
            } else {//大陆支付
                double mmo = Double.parseDouble(moneyStr);
                if (mmo >= 0.01) {
//                    mmo = mmo * 100 ;
                   // login(mmo);
//                    setPayZH(""+mmo);//招行的支付对接，暂时隐藏

                    setPayWX("" + mmo);
                } else {
                    showToast(getResources().getString(R.string.not_0));
                }
            }
        }
    }

    /*-----------------------------------------------招行开始------------------------------------------------------------*/

    private void setPayZH(String money) {
        Intent intentzh = new Intent(RechargeActivity.this, RechargeZHWebViewActivity.class);
        intentzh.putExtra("money", money);
        startActivity(intentzh);
        hideProgress();
    }

    /*-----------------------------------------------招行结束------------------------------------------------------------*/

    /*-----------------------------------------------微信支付开始------------------------------------------------------------*/

    private void setPayWX(String amount) {

        String userId=ToolsUtils.getMyUserId();
        //把需要传给后台的参数写成json然后加密传给后台，加密更安全
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("subject", "余额充值");
        json.put("amount", amount);
        json.put("type", "wxpay");
        json.put("orderType", "0");
        json.put("body", "黑群");

        String content = RequestRSAUtils.setRsaContent(json);

        //这里需要先去服务器请求支付订单信息，然后吊起微信支付
        PGService.getInstance().createRechargeOrder(content)
                //以下是一个个参数传进去，因为后来后台说需要对数据加密，直接全部加密传一个string给他所以注释掉了。
       /* PGService.getInstance().createRechargeOrder(ToolsUtils.getMyUserId(),
                getResources().getString(R.string.yu_e_rechage),
                money,
                "wxpay",
                getResources().getString(R.string.app_name))*/
                .compose(this.<RechargeOrderBean>applyProgress(""))
                .subscribe(new AbsAPICallback<RechargeOrderBean>() {

                    @Override
                    public void onNext(RechargeOrderBean rechargeOrderBean) {

                        JSONObject json = JSON.parseObject(rechargeOrderBean.getOrderString());

                        String partnerId = json.getString("partnerid");
                        String prepayId = json.getString("prepayid");
                        String nonceStr = json.getString("noncestr");
                        String timeStamp = json.getString("timestamp");
                        String sign = json.getString("sign");


                        PayReq req = new PayReq();
                        req.appId			= json.getString("appid");
                        req.partnerId		= json.getString("partnerid");
                        req.prepayId		= json.getString("prepayid");
                        req.nonceStr		= json.getString("noncestr");
                        req.timeStamp		= json.getString("timestamp");
                        req.packageValue	= json.getString("package");
                        req.sign			= json.getString("sign");
                        req.extData			= "app data"; // optional

                        SharedPreferences mysh1=getSharedPreferences("TransferThePossessionOf11", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor=mysh1.edit();
                        editor.putString("appId",req.appId);
                        //editor.putLong("messageid",messageid);
                        editor.commit();

                        System.out.print("test"+req);
//                    Toast.makeText(RechargeActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();

                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        WXPay.requestPay(partnerId, prepayId, nonceStr, timeStamp, sign);
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        showToast(getResources().getString(R.string.get_older_fail));
                    }

                });

    }

    /*-----------------------------------------------微信支付结束------------------------------------------------------------*/

    /*-----------------------------------------------支付宝支付开始------------------------------------------------------------*/
    private static final int SDK_PAY_FLAG = 1;

    private void setPayZFB(String amount) {
        String userId=ToolsUtils.getMyUserId();
        //把需要传给后台的参数写成json然后加密传给后台，加密更安全
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("subject", "余额充值");
        json.put("amount", amount);
        json.put("type", "alipay");
        json.put("orderType", "0");
        json.put("body", "黑群");
        String content = RequestRSAUtils.setRsaContent(json);
        //这里需要先去服务器请求支付订单信息，然后吊起支付宝支付
        PGService.getInstance().createRechargeOrder(content).subscribe(new AbsAPICallback<RechargeOrderBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.get_older_fail));
            }

            @Override
            public void onNext(final RechargeOrderBean rechargeOrderBean) {
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(RechargeActivity.this);
                        Map<String, String> result = alipay.payV2(rechargeOrderBean.getOrderString(), true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();

            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, getResources().getString(R.string.pay_success), Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(EventBusType.RESULT_PAY_WX_SUCCESS);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, getResources().getString(R.string.pay_fail), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    /*-----------------------------------------------支付宝支付结束------------------------------------------------------------*/

    /**
     * 海外用户支付
     */
    private void doOverSeasPay(String moneyStr) {
        showProgress(null);
        String uid = ToolsUtils.getMyUserId();

        String payUrl = "http://120.27.214.115:8088/Checkout/api.php?name=ACU&price=" + moneyStr + "&num=1&total=" + moneyStr + "&uid=" + uid;
        Log.e(TAG, "doOverSeasPay:  这里是支付接口 -------  " + payUrl);

        Intent intent = new Intent(RechargeActivity.this, RechargeWebViewActivity.class);
        intent.putExtra("payUrl", payUrl);
        startActivity(intent);
        hideProgress();

//        mPGservice.getPaypalUrl(uid,"1",moneyStr,"ACU_USD",moneyStr).subscribe(new AbsAPICallback<PayUrlInfoEntity>() {
//            @Override
//            protected void onResultError(ApiException ex) {
//                hideProgress();
//                showToast(getString(R.string.net_visit_exception));
//            }
//
//            @Override
//            public void onNext(PayUrlInfoEntity validateEntivity) {
//                hideProgress();
//                Log.e(TAG, "onNext:  这里获取网络数据=-----");
//                String payUrl = validateEntivity.getInfo().getUrl();
//                if (!(payUrl == null || "".equals(payUrl))) {
//                    Intent intent = new Intent(RechargeActivity.this, RechargeWebViewActivity.class);
//                    intent.putExtra("payUrl", payUrl);
//                    startActivity(intent);
//                }
//            }
//        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s == null || s.equals("")) {
            next.setAlpha(0.5f);
            next.setEnabled(false);
        } else {
            next.setAlpha(1f);
            next.setEnabled(true);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 大陆支付，微信二维码支付，登录
     * {"data":{"username":"1385454002009","token":"E6Tv6goZrQcgVLGWDRrhN1TwWfLTO4sfmzwMaRD2zFOOUN7G"},"code":0,"msg":""}
     */
    private void login(final double moneyStr) {
        showProgress(null);
        PGService.getInstance().login("1385454002009", "123456").subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.weixin_qr_pay_no));
                hideProgress();
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                getAppList(validateEntivity.getToken(), moneyStr);
            }
        });
    }

    /**
     * 获取用户APPID
     */
    private void getAppList(final String token, final double moneyStr) {
        PGService.getInstance().getAppList(token).subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                String appid = "";
                if (ex.getCode() == 0) {
                    weixinAPPIDbean mweixinAPPIDbean = new Gson().fromJson(ex.getDisplayMessage(), weixinAPPIDbean.class);
                    List<weixinAPPIDInfo> mweixinAPPIDInfos = mweixinAPPIDbean.getMweixinAPPIDInfo();
                    if (null != mweixinAPPIDInfos && mweixinAPPIDInfos.size() > 0) {
                        appid = mweixinAPPIDInfos.get(0).getApp_id();
                    }
                    if (null != appid && !"".equals(appid)) {//再去请求
                        getPayCodeUrl(token, appid, moneyStr);
                    } else {
                        showToast(getResources().getString(R.string.weixin_qr_get_no));
                        hideProgress();
                    }
                } else {
                    showToast(getResources().getString(R.string.weixin_qr_get_no));
                    hideProgress();
                }
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_get_no));
            }
        });
    }

    /**
     * 获取自定义二维码
     */
    private void getPayCodeUrl(String token, String appid, final double moneyStr) {
        PGService.getInstance().getPayCodeUrl(token, "" + (int) moneyStr, "ACU", appid).subscribe(new AbsAPICallback<weixinQRData>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_getqr_no));
            }

            @Override
            public void onNext(weixinQRData validateEntivity) {
                wxorders(ToolsUtils.getPhpUid(), validateEntivity.getOut_trade_no(), "" + (moneyStr / 100), validateEntivity.getNative_code_url());
            }
        });
    }

    /**
     * 获取自定义二维码
     */
    private void wxorders(String uid, final String outTradeNo, String money, final String url) {
//        Log.i(TAG, "wxorders: 0001");
        PGService.getInstance().wxorders(uid, outTradeNo, money).subscribe(new AbsAPICallback<weixinBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.weixin_qr_getor_no));
            }

            @Override
            public void onNext(weixinBean validateEntivity) {
                hideProgress();
                /*{"data":{"info":{"ordersn":"2017012450971025"},"debugMsg":"","url":"api\/Api\/wxSaveOrder","msg":"","time":"1485247986"},"code":"1"}*/
                Bundle bundle = new Bundle();
                bundle.putString("self_code_url", url);
                startActivity(ShowQRcodeActivity.class, bundle);
                //目前会出现一种情况，充值保存二维码后再次返回这个页面获取appid的接口会token非法,想直接杀死这个页面
//                scrollToFinishActivity();
            }
        });
    }


}
